const express = require('express')
const router = express.Router()

let db = require('../01-封装函数db')

var jwt = require('jsonwebtoken');

const { md5 } = require('utility');
const utils = require('utility');

//验证数据格式的中间件
router.use((req, res, next) => {
    let { username, password } = req.body
    if (!/^[a-zA-Z][0-9a-zA-Z_]{1,9}$/.test(username)) {  //username.length<2 || username.length>10
        next('用户名长度必须是2~10位')
    } else if (!/^\S{6,12}$/.test(password)) {  //password.length <6 || password.length >12
        next('密码必须是6~12位')
    } else {
        next()
    }
})

//注册接口
router.post('/reguser', function (req, res) {
    let { username, password } = req.body
    // console.log(req.body);
    db.db(`select * from user where username='${username}'`, (e, r) => {
        if (e) throw e
        // console.log(r);
        if (r.length > 0) {
            res.send({ status: 1, message: '用户名已存在' })
        } else {
            //注册前加密密码
            password = utils.md5(password)
            db.db(`insert into user set username="${username}" ,password="${password}"`, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '注册成功' })
            })
        }
    })
})

//登录接口
router.post('/login', function (req, res) {
    let { username, password } = req.body
    password = md5(password)
    // console.log(`select * from user where username="${username}" and password="${password}"`);
    db.db(`select * from user where username="${username}" and password="${password}"`, (err, result) => {
        // console.log(result);
        if (err) throw err
        if (result.length > 0) {
            let token = jwt.sign({ id: result[0].id }, 'shhhhh', { expiresIn: '2h' });
            // console.log(result[0].id);
            res.send({ status: 0, message: '登录成功', token: 'bearer ' + token })
        } else {
            res.send({ status: 1, message: '账号或密码错误' })
        }
    })
})

//错误处理中间件
router.use((err, req, res, next) => {
    //只需要把错误信息响应给客户端
    res.send({ status: 1, message: err })
})
module.exports = router

